package xing.application.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import xing.domain.isv.suite.CorpAuthInfo;
import xing.domain.isv.suite.CorpJSAPITicket;
import xing.infrastructure.util.IdWorker;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/*******************************************************************************************
 * 类描述：  
 *
 * @author: dustin
 * @date： 2017-8-16 10:24
 * @Description:
 * @version 1.0.0
 *
 *
 * Version    Date       ModifiedBy                 Content  
 * -------- ---------    ----------         ------------------------  
 * 1.0.0     2017-8-16    Administrator                            
 *******************************************************************************************
 */
@Service
public class DingApi {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

        public String getToken(){
            try{
                String res = Client.getCommand("gettoken",
                        MessageFormat.format("corpid={0}&corpsecret={1}",Consts.CorpId,Consts.CorpSecret));

                ObjectMapper mapper = new ObjectMapper();
                JsonNode json = mapper.readTree(res);
                if(json.get("errcode").asInt()==0)
                    return json.get("access_token").asText();
                else{
                    throw new Exception(res);
                }
        }catch (Exception e){
            logger.error("获取token失败:{0}",e.getMessage());
            return null;
        }

    }

    public String getTicket(String access_token){

        String res = Client.getCommand("get_jsapi_ticket", "access_token=".concat(access_token));

        return res;
    }


    public String getSuiteToken(String suiteKey,String suiteSecret,String ticket){
        Map<String,String> params = new HashMap<String,String>();
        params.put("suite_key",suiteKey);
        params.put("suite_secret",suiteSecret);
        params.put("suite_ticket",ticket);
        try{
            String res = Client.postCommand("service/get_suite_token",params,null);
            return res;
        }catch (Exception e){
            logger.error("获取suite_token失败",e);
            return null;
        }
    }

    /**
     * 描    述：获取企业的授权信息
     * 创 建 人：陈天龙
     * 日    期：2017/8/24
     * @param suiteKey
     * @param corpId
     * @param suiteAccessToken
     * @return CorpAuthInfo
     */
    public CorpAuthInfo getAuthInfo(String suiteKey, String corpId, String suiteAccessToken){
        logger.info("获取企业的授权信息,参数为suite_key:{},corp_id:{},suite_access_token:{}",suiteKey,corpId,suiteAccessToken);
        Map<String, String> parmMap = new HashMap<String, String>();
        parmMap.put("suite_key", suiteKey);
        parmMap.put("auth_corpid", corpId);
        try {
            String res = Client.postCommand("service/get_auth_info?suite_access_token="+suiteAccessToken,parmMap,null);

            JSONObject jsonObject = JSON.parseObject(res);
            Long errCode = jsonObject.getLong("errcode");
            if (Long.valueOf(0).equals(errCode)) {
                CorpAuthInfo corpAuthInfo = JSON.parseObject(res,CorpAuthInfo.class);
                return corpAuthInfo;
            }
        } catch (IOException e) {
            logger.error("获取auth_info失败",e);
        }
        return null;
    }

    /**
     * 描    述：获取企业的access_token
     * 创 建 人：陈天龙
     * 日    期：2017/8/25
     * @param suiteToken
     * @param corpId
     * @param permanentCode
     * @return String
     */
    public String getCorpToken(String suiteToken,String corpId,String permanentCode){
        logger.info("获取企业的access_token,参数为suiteToken:{},corpId:{},permanentCode:{}",suiteToken,corpId,permanentCode);
        Map<String, String> parmMap = new HashMap<String, String>();
        parmMap.put("permanent_code", permanentCode);
        parmMap.put("auth_corpid", corpId);
        try{
            String res = Client.postCommand("service/get_corp_token?suite_access_token="+suiteToken,parmMap,null);
            return res;
        }catch (Exception e){
            logger.error("获取企业的access_token失败",e);
            return null;
        }
    }

    /**
     * 描    述：获取企业的jsapi ticket
     * 创 建 人：陈天龙
     * 日    期：2017/8/25
     * @param suiteKey
     * @param corpId
     * @param accessToken
     * @return CorpJSAPITicket
     */
    public CorpJSAPITicket getJSTicket(String suiteKey, String corpId, String accessToken) {
        logger.info("获取企业的jsapi ticket,suiteKey:{},corpId:{},accessToken:{}",suiteKey,corpId,accessToken);
        try {
            String res = Client.getCommand("get_jsapi_ticket","access_token="+accessToken);
            JSONObject jsonObject = JSON.parseObject(res);
            Long errCode = jsonObject.getLong("errcode");
            if (Long.valueOf(0).equals(errCode)) {
                String ticket = jsonObject.getString("ticket");
                Long expires_in = jsonObject.getLong("expires_in");
                CorpJSAPITicket corpJSTicket = new CorpJSAPITicket();
                corpJSTicket.setId(IdWorker.nextId());
                corpJSTicket.setCorpId(corpId);
                corpJSTicket.setSuiteKey(suiteKey);
                corpJSTicket.setCorpJsapiTicket(ticket);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.SECOND, expires_in.intValue());
                corpJSTicket.setExpiredTime(calendar.getTime());
                return corpJSTicket;
            }
        } catch (Exception e) {
            logger.error("获取jsapi ticket失败",e);
        }
        return null;
    }
}
